// pages/dish-detail-shared/dish-detail-shared.js
const discoverService = require('../../services/discoverService');
const db = wx.cloud.database();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dishId: '',
    kitchenId: '',
    dish: null,
    kitchen: null,
    isLiked: false,
    isFavorited: false,
    loading: true,
    
    // 评论相关
    comments: [],
    commentText: '',
    showCommentInput: false,
    submitting: false,
    commentsLoading: false,
    hasMoreComments: true,
    currentCommentPage: 0,
    commentPageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { dishId, kitchenId } = options;
    
    this.setData({
      dishId,
      kitchenId
    });
    
    // 加载菜品和厨房数据
    this.loadDishData();
    
    // 加载评论数据
    this.loadComments();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 加载菜品和厨房数据
   */
  loadDishData: function() {
    const { dishId, kitchenId } = this.data;
    
    // 从服务加载菜品数据
    db.collection('mydishes').doc(dishId).get().then(res => {
      const dish = res.data;
      
      if (!dish) {
        wx.showToast({
          title: '菜品不存在',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 检查是否点赞
      this.checkLikeStatus(dishId);
      
      // 检查是否收藏
      this.checkFavoriteStatus(dishId, kitchenId);
      
      // 获取用户信息
      db.collection('myUser').where({
        _id: dish.userId
      }).get().then(userRes => {
        const userInfo = userRes.data[0] || {};
        
        // 设置数据
        this.setData({
          dish: {
            ...dish,
            userInfo
          },
          loading: false
        });
      });
      
      // 如果有厨房ID，则加载厨房数据
      if (kitchenId) {
        db.collection('mykichen').doc(kitchenId).get().then(kitchenRes => {
          this.setData({
            kitchen: kitchenRes.data
          });
        }).catch(err => {
          console.error('加载厨房数据失败', err);
        });
      }
    }).catch(err => {
      console.error('加载菜品数据失败', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    });
  },
  
  /**
   * 检查点赞状态
   */
  checkLikeStatus: function(dishId) {
    // 从 dish_likes 集合中查询当前用户是否点赞
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) return;
    
    db.collection('Like').where({
      userId: userInfo._id,
      dishId: dishId
    }).count().then(res => {
      this.setData({
        isLiked: res.total > 0
      });
    });
  },
  
  /**
   * 检查收藏状态
   */
  checkFavoriteStatus: function(dishId, kitchenId) {
    // 从收藏列表中查询
    const favorites = wx.getStorageSync('myfavorites') || [];
    const isFavorited = favorites.some(fav => 
      fav.dishId === dishId && (!kitchenId || fav.kitchenId === kitchenId)
    );
    
    this.setData({ isFavorited });
  },
  
  /**
   * 点赞菜品
   */
  likeDish: function() {
    const { dishId } = this.data;
    
    discoverService.likeDish(dishId).then(liked => {
      if (liked !== null) {
        // 更新菜品点赞状态和数量
        this.setData({
          isLiked: liked,
          'dish.likeCount': liked 
            ? (this.data.dish.likeCount || 0) + 1 
            : Math.max((this.data.dish.likeCount || 1) - 1, 0)
        });
      }
    });
  },
  
  /**
   * 收藏菜品
   */
  favoriteDish: function() {
    const { dishId, kitchenId } = this.data;
    
    discoverService.favoriteDish(dishId, kitchenId).then(favorited => {
      if (favorited !== null) {
        this.setData({ isFavorited: favorited });
        
        wx.showToast({
          title: favorited ? '已收藏' : '已取消收藏',
          icon: 'success'
        });
      }
    });
  },
  
  /**
   * 显示评论输入框
   */
  showCommentInput: function() {
    this.setData({ showCommentInput: true });
  },
  
  /**
   * 隐藏评论输入框
   */
  hideCommentInput: function() {
    this.setData({ 
      showCommentInput: false,
      commentText: ''
    });
  },
  
  /**
   * 输入评论内容
   */
  onCommentInput: function(e) {
    this.setData({ commentText: e.detail.value });
  },
  
  /**
   * 提交评论
   */
  submitComment: function() {
    const { dishId, commentText } = this.data;
    
    if (!commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ submitting: true });
    
    discoverService.addComment(dishId, commentText).then(comment => {
      if (comment) {
        // 更新评论列表和菜品评论数
        const newComments = [comment, ...this.data.comments];
        
        this.setData({
          comments: newComments,
          commentText: '',
          showCommentInput: false,
          submitting: false,
          'dish.commentCount': (this.data.dish.commentCount || 0) + 1
        });
        
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });
      } else {
        this.setData({ submitting: false });
        
        wx.showToast({
          title: '评论失败',
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 加载评论
   */
  loadComments: function() {
    if (!this.data.hasMoreComments || this.data.commentsLoading) return;
    
    const { dishId, currentCommentPage, commentPageSize } = this.data;
    
    this.setData({ commentsLoading: true });
    
    discoverService.getComments(dishId, commentPageSize, currentCommentPage * commentPageSize)
      .then(comments => {
        // 合并评论数据
        const newComments = currentCommentPage === 0 
          ? comments 
          : [...this.data.comments, ...comments];
        
        this.setData({
          comments: newComments,
          hasMoreComments: comments.length === commentPageSize,
          currentCommentPage: currentCommentPage + 1,
          commentsLoading: false
        });
      })
      .catch(err => {
        console.error('加载评论失败', err);
        this.setData({ commentsLoading: false });
      });
  },
  
  /**
   * 添加到饮食计划
   */
  addToMealPlan: function() {
    const { dish } = this.data;
    
    wx.navigateTo({
      url: '/pages/mealplan/mealplan'
    });
  },
  
  /**
   * 返回上一页
   */
  navigateBack: function() {
    wx.navigateBack();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const { dish, dishId, kitchenId } = this.data;
    
    let path = `/pages/dish-detail-shared/dish-detail-shared?dishId=${dishId}`;
    if (kitchenId) {
      path += `&kitchenId=${kitchenId}`;
    }
    
    return {
      title: dish ? dish.name : '分享菜品',
      path: path,
      imageUrl: dish && dish.image ? dish.image : ''
    };
  }
})